// 分离音频和视频, 并且分别发送到不同端口
// 并且生成可供给fplay使用的sdp文件
use webrtc::peer_connection::RTCPeerConnection;
use webrtc::rtp_transceiver::rtp_codec::RTPCodecType;
use super::send_rtp_to_udp::send_rtp_to_udp;
use crate::media::sdp::generate_sdp;
use anyhow::Result;
use crate::web_rtc::audio_addr;
use crate::web_rtc::video_addr;
use once_cell::sync::Lazy;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;

pub static AUDIO_TRACK_STATUS: Lazy<Arc<AtomicBool>> = Lazy::new(|| Arc::new(AtomicBool::new(false)));
pub static VIDEO_TRACK_STATUS: Lazy<Arc<AtomicBool>> = Lazy::new(|| Arc::new(AtomicBool::new(false)));

pub async fn check_tracks_status() {
    println!("check_tracks_status");
    let (audio_track_status, video_track_status) = (AUDIO_TRACK_STATUS.clone(), VIDEO_TRACK_STATUS.clone());
    loop {
        if audio_track_status.load(Ordering::SeqCst) && video_track_status.load(Ordering::SeqCst) {
            println!("音频和视频轨道均已准备好");
            break;
        }
        println!("等待音频和视频轨道准备好...");
        // 避免异步阻塞
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    };
}

pub async fn divide_audio_video(peer_connection: &RTCPeerConnection) {

    println!("进入divide_audio_video函数");
    peer_connection.on_track(Box::new(move |track, receiver, sender| {
        let (audio_track_status, video_track_status) = (AUDIO_TRACK_STATUS.clone(), VIDEO_TRACK_STATUS.clone());
        let kind = track.kind();
        let track_clone = track.clone();

        println!("进入on_track回调, 轨道类型: {:?}", kind);
        tokio::spawn(async move {
            println!("Track has started, of type: {:?}", kind);
            let codec = track_clone.codec();
            println!("🎧 收到 {:?} 轨道", kind);
            println!("📦 编码格式: {}", codec.capability.mime_type);
            let sdp = generate_sdp(&codec.capability.mime_type, codec.payload_type).unwrap();
            let sdp_fmtp = codec.capability.sdp_fmtp_line.clone();
            println!("sdp_fmtp: {:?}", sdp_fmtp);
            // 获取音频或视频的sps和pps, 防止解析错误
            let (mut sps, mut pps) = (Vec::new(), Vec::new());
            if let Some(sprop) = sdp_fmtp.split(';').find(|s| s.trim().starts_with("sprop-parameter-sets=")) {
                let sets = sprop.trim().trim_start_matches("sprop-parameter-sets=");
                let mut parts = sets.split(',');
                sps = parts.next().and_then(|s| STANDARD.decode(s).ok()).unwrap_or_default();
                pps = parts.next().and_then(|s| STANDARD.decode(s).ok()).unwrap_or_default();
            }            
            let payload_type = codec.payload_type;
            // if !sps.is_empty() && !pps.is_empty() {
            //     println!("✅ SPS/PPS 提取成功: SPS {} bytes, PPS {} bytes", sps.len(), pps.len());
            // } else {
            //     println!("⚠️ 未能提取 SPS/PPS，可能 SDP 格式异常");
            // }
            match kind {
                RTPCodecType::Audio => {
                    // 音频轨道
                    // 设置音频轨道状态为true
                    audio_track_status.store(true, Ordering::SeqCst);
                    write_to_sdp_file(codec_type::Audio, sdp).unwrap();
                    send_rtp_to_udp(track_clone, audio_addr, payload_type, false).await;
                }
                RTPCodecType::Video => {
                    // 视频轨道
                    // 设置视频轨道状态为true
                    video_track_status.store(true, Ordering::SeqCst);
                    write_to_sdp_file(codec_type::Video, sdp).unwrap();
                    send_rtp_to_udp(track_clone, video_addr, payload_type, true).await;
                }
                _ => {
                    // 未指定
                    println!("不支持的轨道类型: {:?}", kind);
                }
            }
        });
        return Box::pin(async{});
    })
    
);
    
}
enum codec_type {
    Audio,
    Video,
}
use crate::get_path::get_path;
use std::{fs::write, path::PathBuf};
fn write_to_sdp_file(codec_type: codec_type, sdp: String) -> Result<()> {
    let mut path:PathBuf = PathBuf::new();
    match codec_type {
        codec_type::Audio => {
            path = get_path().join("sdp").join("AudioSDP.sdp");
        }
        codec_type::Video => {
            path = get_path().join("sdp").join("VideoSDP.sdp");
        }
    };

    // 确保目录存在
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).unwrap();
    }

    write(path, sdp).unwrap();
    return Ok(());
}